import axios from "axios";
import store from "../../../store";
import initLinkedList from "../initLinkedList";
import testData from "../testData";
import getTemplateByStoreCode from "../getTemplateByStoreCode";
import getUrlSearch from "../../getUrlSearch"
import { getUserInfo } from "../getUserInfo";
// import testData from "./preData";
let getHttp = () => {
    return location.href.match(/^(http|https)\:.+/)[1];
}
// console.log("拿到的地址", window.location);
let host = (window.location.host.indexOf("localhost") > -1 ||
    window.location.host.indexOf("127.0.0.1") > -1) ? "https://test-njxs.weilian.cn" :
        `${getHttp()}://` + window.location.hostname;
// let host = "http://" + window.location.host;
// let host = "https://test-njxs.weilian.cn";//新测试地址
// let host = "https://test-njxs.weilian.cn";//测试
// let host = "https://njxs.weilian.cn";//生产
// let host = "http://uat.njxs.weilian.cn";//演示
// let host = "https://pre-njxs.weilian.cn";//预发布
console.log("拿到的地址", host);

//设置后台管理系统的sessionId
// setTimeout(() => {
//     setCookie('sessionId',"c2403be2040d436b89fb1cabe5c18862")
// }, 500);

const TP_KEY = "mall_templet";
const SUYUAN = "zy_mall_traceSource_url";
const BASE_HOST = "zy_mall_base_url";
const GOODS_HOST = "zy_mall_goods_url";
const TRADE_HOST = "zy_mall_trade_url";
const CUSTOMER_HOST = "zy_mall_customer_url";
const SERVICE_HOST = "zy_mall_service_url";
const ENTERPRISE_CODE = "enterpriseCode";
const STORE_CODE = "";
const FILE_HOST = "FILE_HOST";

let config = {
    "local_host": host,//域名
    "base_host": "http://test.vmbase.scn.weilian.cn",//172.19.6.152:33001
    "goods_host": "http://test.vmgoods.scn.weilian.cn",//172.19.6.152:33002
    "trade_host": "http://test.vmtrade.scn.weilian.cn",//172.19.6.152:33003
    "customer_host": "http://test.vmcustomer.scn.weilian.cn",//172.19.6.152:33004
    //      "customer_host": "172.19.6.152:33004",//172.19.6.152:33004
    "service_host": "http://test.vmservice.scn.weilian.cn",//172.19.6.152:33005,
    //运营后台查询首页配置相关数据（sessionId与商城首页查询的接口不同---通过getCookie("sessionId")获取）
    "config_host": "http://test.vmgoods.scn.weilian.cn",
    "config_commend": "/resourceConfig/resource/commend",
    "config_feature": "/resourceConfig/resource/feature",
    "config_ad": "/resourceConfig/resource/ad",
    "config_meal": "/resourceConfig/resource/meal",
    "config_category": "/resourceConfig/resource/category",
    //商城首页查询广告/餐点/分类等信息---通过localStorage.getItem("sessionId")获取
    "home_commend": "/resourceConfig/mobile/commend",
    "home_feature": "/resourceConfig/mobile/feature",
    "home_ad": "/resourceConfig/mobile/ad",
    "home_meal": "/resourceConfig/mobile/meal",
    "home_category": "/resourceConfig/mobile/category",
    //查询配置相关的一些参数
    "config_params": "/mallconfig/selectVO",
    "alertTime": 500,//弹出提示时间
    "alertTime_1": 500,//弹出提示时间
    "alertTime_2": 2000,//弹出提示时间
    "storeCode": "1613",
    "storeId": "1613",
    "enterpriseCode": "enterpriseCode",
    "mall_file_host": "http://files.scn.weilian.cn",
    "FILE_HOST": "http://files.scn.weilian.cn",
    "traceSource": "http://test.sale.scn.weilian.cn:81/sale/H5/wnmobile/origins/index.html"//溯源码地址
}
//拿到模板之类的启动参数
function initTemplateParams(data) {
    // for (let item of data) {
    //     if (item.key === TP_KEY) {
    // let config = JSON.parse(item.value);
    let config = data;
    console.log("打印config",config)
    store.commit("setConfigParams", config);
    console.log("打印config.templateConfigList",config.templateConfigList)
    let specialTemplate = setSpecialTemplateParams(config.templateConfigList);
    let manifest = {};
    //前台页面注入manifest
    // if (window.environment === "production") {
        manifest = initLinkedList(JSON.parse(
            config.templateConfigList.find(item => item.tpState ===1).tpConfig
        ));
        //暂时先用本地死数据(线上去掉下面这句)
        // manifest = initLinkedList(JSON.parse(testData))
        //如果存在活动页面（自定义页面），也要注入manifest中
        if (specialTemplate) {
            manifest = {
                ...manifest,
                ...initLinkedList(JSON.parse(specialTemplate.tpConfig))
            }
        }
    // }
    console.log("manifest",manifest)
    window.manifest = manifest;
    return config;
    //     }
    // }
}
//初始化接口
function initInterface(data) {
    let obj = {};
    let reg = /^http:\/\/.+$/;
    data.forEach((item) => {
        if (item.key !== TP_KEY) {
            if (item.key === "goods_host" || item.key === "mall_file_host") {
                if (item.value.lastIndexOf("/") === (item.value.length - 1)) {
                    obj[item.key] = item.value.slice(0, item.value.length - 1);
                } else {
                    obj[item.key] = item.value;
                }
            } else {
                obj[item.key] = item.value;
            }
            // obj[item.key] = reg.test(item.value) ? item.value.slice(0, item.value.length - 1) : item.value;
            // obj[item.key] = item.key === "goods_host" ? item.value.slice(0, item.value.length - 1) : item.value;
        }
    });
    //特殊情况额外处理
    //溯源链接
    obj.traceSource = obj[SUYUAN];
    //config_host
    obj.config_host = obj.goods_host;
    obj["FILE_HOST"] = obj["mall_file_host"];
    // obj.base_host = obj[BASE_HOST];
    // obj.customer_host = obj[CUSTOMER_HOST];
    // obj.trade_host = obj[TRADE_HOST];
    // obj.service_host = obj[SERVICE_HOST];
    // obj.goods_host = obj[GOODS_HOST];
    //企业code
    //门店ID
    //门店Code
    obj.enterpriseCode = obj.zy_mall_uc_enterprisecode;
    console.log("obj", obj);
    window.api = Object.assign(config, {...obj});
    window.api.storeCode = getUrlSearch().storeCode || window.api.yxzx_deptoid;
    window.api.storeId = getUrlSearch().storeCode || window.api.yxzx_deptoid;

    //设置门店id
    localStorage.setItem("storeCode", window.api.storeCode);
    localStorage.setItem("storeId", window.api.storeId);
}
//判断商城状态
function judgeShopState(result) {
    let obj = result;
    // console.log(obj);
    if (obj.runStatus) {
        return true;
    } else {
        return false;
    }
}
//设置保存新增页面的方法
function setSpecialTemplateParams(list) {
    // console.log("打印SpecialTemplateParams", list);
    // let exits = false;
    let specialTemplate = list.find(item => item.tpDesc === "specialtemplateforaddpages");
    if (specialTemplate) {
        store.commit("gw/setSpecialTemplate", JSON.parse(specialTemplate.tpConfig));
        console.log("JSON.parse(specialTemplate.tpConfig)", JSON.parse(specialTemplate.tpConfig));
        if (window.environment === "edit") {
            store.commit("gw/setSpecialTemplateParams", specialTemplate);
            store.commit("gw/setNeedUploadSpecialTemplate", false);
        }
        return specialTemplate;
    }
    return store.commit("gw/setNeedUploadSpecialTemplate", true);
}
// function resetStoreCode(storeCode) {
// 	window.api.storeCode = storeCode;
//     window.api.storeId = storeCode;
//     localStorage.setItem("storeCode", window.api.storeCode);
//     localStorage.setItem("storeId", window.api.storeId);
// }
export default () => {
    let options = {
        method: "post",
        data: {"parameterStr":[
            "base_host",
            "goods_host",
            "trade_host",
            "customer_host",
            "service_host",
            "zy_mall_traceSource_url",
            "zy_mall_uc_enterprisecode",
            "yxzx_deptoid",
            // "mall_templet",
            "crm_customer_service_host",
            "ios_pay_version",
            "android_pay_version",
            "ios_pay_update",
            "android_pay_update",
            "njxs_mall_erp_goods_host",
            "njxs_mall_erp_enterpriseid",
            "mall_file_host",
            "tmsUrl"
        ]},
        url: host + "/resourceLevel/getMallParameter",
        timeout: 10000
    }
    return new Promise(resolve => {
        // console.log("请求的地址", options.url);
        axios(options).then(async data => {
            if (data.status === 200 && data.data.returnCode === 1 && data.data.data[0]) {
                let result = data.data.data[0];
                //初始化模板相关的参数并拿到该参数
                //storeCode
                initInterface(result);
                //拿到storeCode
                // let userInfo = await getUserInfo();
                // resetStoreCode(userInfo.lastStoreCode);
                let templateRes = await getTemplateByStoreCode();
                // return console.log(templateRes);
                let tpValue = initTemplateParams(templateRes.data.data[0]);
                resolve(judgeShopState(tpValue));
            }
            resolve();
        });
    });
}
